<template>
  <view class="min-h-screen flex flex-col bg-[#f5f5f5]">
    <!-- 固定头部区域 -->
    <view class="fixed-top left-0 right-0 z-50">
      <S1Header title="常用货品" :on-back="handleBack" />

      <view class="flex items-center bg-white px-20rpx py-12rpx">
        <view class="relative h-70rpx flex flex-1 items-center rounded-full bg-[#f5f5f5] px-20rpx">
          <image src="https://ceshiweb.picaime.com/static/images/search.png" class="mr-10rpx h-36rpx w-36rpx" />
          <input
            v-model="keywords" class="flex-1 text-28rpx" placeholder="搜索货品名称或编号" confirm-type="search"
            @confirm="onSearch"
          >
          <view
            v-if="keywords" class="absolute right-20rpx h-40rpx w-40rpx flex items-center justify-center"
            @click="clearKeyword"
          >
            <image class="h-36rpx w-36rpx" src="https://ceshiweb.picaime.com/static/images/close.png" />
          </view>
        </view>
      </view>
    </view>
    <!-- 分类筛选区域 - 普通布局，占据文档流位置 -->
    <view class="category-filter-container">
      <!-- 一级分类 -->
      <scroll-view class="category-scroll-row" scroll-x enable-flex>
        <!-- 全部分类 -->
        <view
          class="category-tag" :class="{ active: selectedCategory.id === 'all' }"
          @click="selectCategory({ id: 'all', name: '全部分类' })"
        >
          <text class="category-tag-text">
            全部分类
          </text>
        </view>

        <!-- 分类列表 -->
        <view
          v-for="category in categoryList" :key="category.id" class="category-tag parent-tag" :class="{
            'active': selectedCategory.id === category.id,
            'has-children': category.child && category.child.length > 0,
          }" @click="selectCategory({ id: category.id, name: category.name })"
        >
          <text class="category-tag-text">
            {{ category.name }}
          </text>
        </view>

        <!-- 未分类 -->
        <view
          class="category-tag" :class="{ active: selectedCategory.id === 'uncategorized' }"
          @click="selectCategory({ id: 'uncategorized', name: '未分类' })"
        >
          <text class="category-tag-text">
            未分类
          </text>
        </view>
      </scroll-view>

      <!-- 二级分类 -->
      <transition name="slide-down">
        <scroll-view
          v-if="selectedParentCategory && selectedParentCategory.child && selectedParentCategory.child.length > 0"
          class="subcategory-scroll-row" scroll-x enable-flex
        >
          <view
            v-for="child in selectedParentCategory.child" :key="child.id" class="category-tag child-tag"
            :class="{ active: selectedCategory.id === child.id }"
            @click="selectCategory({ id: child.id, name: child.name, parent_id: child.parent_id })"
          >
            <text class="category-tag-text">
              {{ child.name }}
            </text>
          </view>
        </scroll-view>
      </transition>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view class="pb-[60px]" scroll-y @scrolltolower="onLoadMore">
      <view v-if="goodsList.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">
          📦
        </text>
        <text class="empty-text">
          暂无货品数据
        </text>
        <text class="empty-desc">
          当前分类下还没有货品<br>点击下方按钮添加第一个货品
        </text>
        <button class="add-btn" @tap="handleAddGoods">
          添加货品
        </button>
      </view>
      <view v-if="loading && goodsList.length === 0" class="loading-state">
        <view class="loading-spinner" />
        <text class="text-28rpx text-[#999]">
          加载中...
        </text>
      </view>

      <!-- 货品列表 -->
      <view v-for="(item, index) in goodsList" :key="index" class="goods-card" @tap="selectGoodsItem(item)">
        <view class="card-checkbox" @tap.stop="changeCommonlyUsedCheckbox(item)">
          <checkbox
            :checked="selectedGoodsIds.includes(item.goods_id)" class="scale-80 transform"
            style="color: #ddd"
          />
        </view>
        <view class="card-img">
          <image :src="getFullUrl(item.original_img)" class="h-90rpx w-90rpx rounded-[4px]" />
        </view>
        <view class="card-content">
          <text class="card-title">
            {{ item.goods_name }}
          </text>
          <!-- 规格 -->
          <view class="flex flex-wrap gap-10rpx">
            <view v-for="(guige, idx) in item.goods_guige" :key="idx" class="card-unit">
              1{{ guige.relation }}={{ guige.num }}{{ guige.unit }}
            </view>
            <view v-if="item.goods_guige.length === 0" class="card-unit">
              无定装按{{ item.unit }}卖
            </view>
          </view>
          <!-- 附加费 -->
          <view class="flex flex-wrap gap-10rpx">
            <view v-for="(fujiafei, idx) in item.goods_fujiafei" :key="idx" class="text-24rpx text-[#666]">
              {{ fujiafei.name }} {{ fujiafei.rate }}
            </view>
            <view v-if="item.goods_fujiafei.length === 0" class="text-24rpx text-[#666]">
              无附加费
            </view>
          </view>
        </view>
        <view class="card-edit">
          <view class="edit-btn" @click.stop="handleEditGoods(item)">
            编辑
          </view>
        </view>
      </view>

      <view v-if="loading && goodsList.length > 0" class="flex items-center justify-center py-20rpx">
        <text class="text-28rpx text-[#999]">
          加载中...
        </text>
      </view>
      <view v-if="noMore && goodsList.length > 0" class="flex items-center justify-center py-20rpx">
        <text class="text-28rpx text-[#999]">
          没有更多数据了
        </text>
      </view>
      <view class="h-32rpx" />
    </scroll-view>

    <!-- 悬浮添加按钮 -->
    <view
      v-if="!fromBatchOrCategory"
      class="fixed right-30rpx h-100rpx w-100rpx flex items-center justify-center rounded-full bg-[#43CF7C] shadow-md"
      style="bottom: 100px" @click="handleAddGoods"
    >
      <text class="text-60rpx text-white font-light">
        +
      </text>
    </view>

    <!-- 底部状态栏 -->
    <view class="goods-footer-bar">
      <view class="footer-left" @click="toggleSelectAll">
        <view class="footer-checkbox" :class="{ checked: isAllSelected }" />
        <text class="footer-status">
          已勾选{{ selectedCount }}个货品
        </text>
      </view>
      <template v-if="fromBatchOrCategory">
        <view class="footer-btn footer-btn-type" @click="handleBatchImport">
          批量导入
        </view>
      </template>
      <template v-else>
        <view class="footer-btn footer-btn-del" @click="handleBatchDelete">
          批量删除
        </view>
        <view class="footer-btn footer-btn-type" @click="handleBatchChangeCategory">
          批量更改分类
        </view>
      </template>
    </view>

    <!-- 批量更改分类弹窗 -->
    <up-popup :show="showCategoryChangeModal" mode="bottom" :round="10" @close="showCategoryChangeModal = false">
      <view>
        <view class="mb-10rpx w-full flex justify-center" @click="showCategoryChangeModal = false">
          <view class="h-10rpx w-30rpx rounded-full bg-[#ddd]" />
        </view>
        <view class="filter-content p-30rpx pb-10rpx">
          <view class="mb-16rpx flex items-center justify-between">
            <view class="flex items-center">
              <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
              <text class="text-32rpx text-[#333]">
                更改分类
              </text>
            </view>
            <view class="flex gap-20rpx">
              <text class="text-28rpx text-[#666]" @click="showCategoryChangeModal = false">
                取消
              </text>
              <text class="text-28rpx text-[#07c160]" @click="confirmCategoryChange">
                确定
              </text>
            </view>
          </view>

          <!-- 一级分类选择 -->
          <view class="form-row mb-20rpx" @click="showPrimaryCategoryModal = true">
            <text class="form-label">
              一级分类
            </text>
            <view class="form-input flex items-center justify-between">
              <text>{{ selectedPrimaryCategory?.name || '请选择一级分类' }}</text>
              <image src="/static/images/select.png" class="h-20rpx w-10rpx" />
            </view>
          </view>

          <!-- 二级分类选择 -->
          <view v-if="selectedPrimaryCategory" class="form-row" @click="showSecondaryCategoryModal = true">
            <text class="form-label">
              二级分类
            </text>
            <view class="form-input flex items-center justify-between">
              <text>{{ selectedSecondaryCategory?.name || '请选择二级分类' }}</text>
              <image src="/static/images/select.png" class="h-20rpx w-10rpx" />
            </view>
          </view>
        </view>
      </view>
    </up-popup>

    <!-- 一级分类选择弹窗 -->
    <up-popup :show="showPrimaryCategoryModal" mode="bottom" :round="10" @close="showPrimaryCategoryModal = false">
      <view>
        <view class="mb-10rpx w-full flex justify-center" @click="showPrimaryCategoryModal = false">
          <view class="h-10rpx w-30rpx rounded-full bg-[#ddd]" />
        </view>
        <view class="filter-content p-30rpx pb-10rpx">
          <view class="mb-16rpx flex items-center">
            <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
            <text class="text-32rpx text-[#333]">
              选择一级分类
            </text>
          </view>
          <view class="mt-10rpx max-h-400rpx overflow-y-auto">
            <view
              v-for="(item, index) in categoryList" :key="index"
              class="border-b border-[#f0f0f0] px-0 py-24rpx text-center text-32rpx text-[#333]"
              @click="selectPrimaryCategory(item)"
            >
              {{ item?.name || "" }}
            </view>
          </view>
        </view>
      </view>
    </up-popup>

    <!-- 二级分类选择弹窗 -->
    <up-popup :show="showSecondaryCategoryModal" mode="bottom" :round="10" @close="showSecondaryCategoryModal = false">
      <view>
        <view class="mb-10rpx w-full flex justify-center" @click="showSecondaryCategoryModal = false">
          <view class="h-10rpx w-30rpx rounded-full bg-[#ddd]" />
        </view>
        <view class="filter-content p-30rpx pb-10rpx">
          <view class="mb-16rpx flex items-center">
            <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
            <text class="text-32rpx text-[#333]">
              选择二级分类
            </text>
          </view>
          <view class="mt-10rpx max-h-400rpx overflow-y-auto">
            <view
              v-for="(item, index) in secondaryCategoryList" :key="index"
              class="border-b border-[#f0f0f0] px-0 py-24rpx text-center text-32rpx text-[#333]"
              @click="selectSecondaryCategory(item)"
            >
              {{ item?.name || "" }}
            </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import type { CategoryItem } from '@/api/category/types';
import type {
  CategoryGoodsItem,
} from '@/api/order/types';
import { computed, ref, watch } from 'vue';
import { getCategoryTwo, getDayReport } from '@/api/category';
import { edcategory, exportGoodsData, getSelfCategoryGoods, updateSelfStatus } from '@/api/order';
import * as S1Header from '@/components/S1Header.vue';

// 基础数据
const keywords = ref('');
const totalGoods = ref(0);
const loading = ref(false);
const refreshing = ref(false);
const noMore = ref(false);
const page = ref(1);
const pageSize = ref(10);

// 防抖定时器
let searchDebounce: ReturnType<typeof setTimeout> | null = null;

// 分类筛选相关
const categoryList = ref<CategoryItem[]>([]);
const selectedCategory = ref<{
  id: number | string;
  name: string;
  parent_id?: number;
}>({
  id: 'all',
  name: '全部分类',
});
const selectedParentCategory = ref<CategoryItem | null>(null);

// 货品列表
const goodsList = ref<CategoryGoodsItem[]>([]);
// 已选择的货品ID列表
const selectedGoodsIds = ref<number[]>([]);

// 批量更改分类相关状态
const showCategoryChangeModal = ref(false); // 分类更改弹窗
const showPrimaryCategoryModal = ref(false); // 一级分类选择弹窗
const showSecondaryCategoryModal = ref(false); // 二级分类选择弹窗
const secondaryCategoryList = ref<any[]>([]); // 二级分类列表
const selectedPrimaryCategory = ref<any>(null); // 选中的一级分类
const selectedSecondaryCategory = ref<any>(null); // 选中的二级分类

// 计算已选择的货品数量
const selectedCount = computed(() => selectedGoodsIds.value.length);

// 判断是否全部选中
const isAllSelected = computed(() => {
  return goodsList.value.length > 0 && selectedGoodsIds.value.length === goodsList.value.length;
});

// 监听搜索关键词变化
watch(keywords, () => {
  // 清除之前的定时器
  if (searchDebounce) clearTimeout(searchDebounce);

  // 设置新的定时器，延迟300ms执行搜索
  searchDebounce = setTimeout(() => {
    loadData(true);
  }, 300);
});

// URL参数相关
const fromBatchOrCategory = ref(false);
const urlParams = ref({
  huozhu_id: '',
  huozhu_name: '',
  catid: '',
  catid_2: '',
  pici: '', // 批次号
  pici_id: '', // 批次ID
});

// 获取URL参数 - 适配uniapp onShow生命周期
const getURLParams = (options?: any) => {
  const pageOptions = options;
  if (pageOptions) {
    // 保存URL参数
    urlParams.value = {
      huozhu_id: pageOptions.huozhu_id || '',
      huozhu_name: pageOptions.huozhu_name ? decodeURIComponent(pageOptions.huozhu_name) : '',
      catid: pageOptions.catid || '',
      catid_2: pageOptions.catid_2 || '',
      pici: pageOptions.pici || '', // 批次号
      pici_id: pageOptions.pici_id || '', // 批次ID
    };

    // 判断是否来自批次库存或分类库存
    fromBatchOrCategory.value = !!(urlParams.value.huozhu_id || urlParams.value.catid);

    console.log('接收到的URL参数:', urlParams.value);
    console.log('是否来自批次或分类:', fromBatchOrCategory.value);
  }
  else {
    console.log('无法获取页面参数');
  }
};

// 页面显示时触发 - uniapp生命周期，接收传递的参数
onShow(() => {
  const allPages = getCurrentPages();
  const lastPages = allPages.length - 1;
  const options = allPages[lastPages].options;

  // 获取URL参数，优先使用onShow传入的参数
  getURLParams(options);
  // 获取分类数据
  getCategoryData();
  // 加载数据
  loadData(true);
});

// 页面操作
function handleBack() {
  uni.navigateBack();
}

function onSearch() {
  console.log('搜索:', keywords.value);
  loadData(true);
}

function clearKeyword() {
  keywords.value = '';
  loadData(true);
}

// 分类筛选相关函数

function selectCategory(category: { id: number | string; name: string; parent_id?: number }) {
  selectedCategory.value = category;

  // 更新选中的父分类，用于显示二级分类
  if (category.id === 'all' || category.id === 'uncategorized') {
    // 选中全部分类或未分类时，清空父分类
    selectedParentCategory.value = null;
  }
  else if (category.parent_id) {
    // 选中二级分类时，保持当前父分类
    // selectedParentCategory.value 保持不变
  }
  else {
    // 选中一级分类时，查找对应的分类对象
    const parentCategory = categoryList.value.find((cat: CategoryItem) => cat.id === category.id);
    selectedParentCategory.value = parentCategory || null;
  }

  loadData(true);
}

// 获取分类数据
async function getCategoryData() {
  try {
    const res = await getDayReport({
      page: 1,
      ishuozhuorfenlei: 1,
      limit: 10000,
      date: '', // 日期参数
    });

    if (res.code === 200 && res.data && res.data.data) {
      categoryList.value = res.data.data;
    }
  }
  catch (error) {
    console.error('获取分类失败', error);
  }
}

// 列表相关
function onPullDown() {
  console.log('下拉刷新');
  refreshing.value = true;
  loadData(true).finally(() => {
    refreshing.value = false;
  });
}

function onLoadMore() {
  console.log('加载更多');
  if (loading.value || noMore.value) return;
  loadData();
}

async function loadData(reset = false) {
  if (reset) {
    page.value = 1;
    noMore.value = false;
  }

  loading.value = true;
  try {
    const params: any = {
      page: page.value,
      limit: pageSize.value,
      goods_name: keywords.value,
      key: 0,
      new_pici: false,
      bind: '',
      last_pici_id: '',
      pici_id: 0,
      index: 0,
    };

    if (selectedCategory.value.id === 'all') {
      params.key = 0;
    }
    else if (selectedCategory.value.id === 'uncategorized') {
      params.key = -1;
    }
    else {
      params.key = Number(selectedCategory.value.id);
      if (selectedCategory.value.parent_id) {
        params.self_catid = selectedCategory.value.parent_id;
        params.self_catid_2 = Number(selectedCategory.value.id);
      }
      else {
        params.self_catid = Number(selectedCategory.value.id);
        params.self_catid_2 = '';
      }
    }

    console.log('API调用参数:', params);
    const res = await getSelfCategoryGoods(params);

    if (reset) {
      goodsList.value = res.data.data.data;
    }
    else {
      goodsList.value = [...goodsList.value, ...res.data.data.data];
    }

    totalGoods.value = res.data.data.total;
    noMore.value = goodsList.value.length >= totalGoods.value;
    page.value++;
  }
  catch (error) {
    console.error('加载数据失败', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none',
    });
  }
  finally {
    loading.value = false;
  }
}

// 货品操作
function handleAddGoods() {
  uni.navigateTo({
    url: '/pages/common/goods/add',
  });
}

function handleEditGoods(item: CategoryGoodsItem) {
  // 将商品数据存储到缓存中
  uni.setStorageSync('editGoodsData', item);

  // 跳转到编辑页面
  uni.navigateTo({
    url: `/pages/common/goods/add?mode=edit&id=${item.goods_id}`,
  });
}

function handleDeleteGoods(item: CategoryGoodsItem) {
  uni.showModal({
    title: '提示',
    content: `确定要删除货品"${item.goods_name}"吗？`,
    success(res) {
      if (res.confirm) {
        // TODO: 实现删除逻辑
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        });
      }
    },
  });
}

function selectGoodsItem(item: CategoryGoodsItem) {
  // 切换商品选中状态
  changeCommonlyUsedCheckbox(item);
}

function changeCommonlyUsedCheckbox(item: CategoryGoodsItem) {
  const index = selectedGoodsIds.value.indexOf(item.goods_id);
  if (index > -1) {
    // 如果已经选中，则取消选中
    selectedGoodsIds.value.splice(index, 1);
  }
  else {
    // 如果未选中，则选中
    selectedGoodsIds.value.push(item.goods_id);
  }
  console.log('选中商品ID:', selectedGoodsIds.value);
}

function getFullUrl(url: string) {
  return url;
}

// 切换全选/取消全选
function toggleSelectAll() {
  if (isAllSelected.value) {
    // 如果当前是全选状态，则取消全选
    selectedGoodsIds.value = [];
  }
  else {
    // 如果当前不是全选状态，则全选
    selectedGoodsIds.value = goodsList.value.map((item: CategoryGoodsItem) => item.goods_id);
  }
}

// 处理批量删除
function handleBatchDelete() {
  if (selectedGoodsIds.value.length === 0) {
    uni.showToast({
      title: '请先选择要删除的货品',
      icon: 'none',
    });
    return;
  }

  uni.showModal({
    title: '提示',
    content: `确定要删除选中的${selectedGoodsIds.value.length}个货品吗？`,
    success(res) {
      if (res.confirm) {
        // 调用批量删除接口
        const params = {
          status: 1, // 固定传1
          editShangpinId: selectedGoodsIds.value,
        };

        console.log('批量删除参数:', params);

        updateSelfStatus(params)
          .then((res: any) => {
            if (res.code === 200) {
              uni.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
              });

              // 清空选中状态
              selectedGoodsIds.value = [];
              // 重新加载数据
              loadData(true);
            }
            else {
              uni.showToast({
                title: res.msg || '删除失败',
                icon: 'none',
                duration: 2000,
              });
            }
          })
          .catch((err: any) => {
            console.error('批量删除失败:', err);
            uni.showToast({
              title: '删除失败',
              icon: 'none',
              duration: 2000,
            });
          });
      }
    },
  });
}

// 处理批量更改分类
function handleBatchChangeCategory() {
  if (selectedGoodsIds.value.length === 0) {
    uni.showToast({
      title: '请先选择要更改分类的货品',
      icon: 'none',
    });
    return;
  }

  // 重置选择状态
  selectedPrimaryCategory.value = null;
  selectedSecondaryCategory.value = null;
  secondaryCategoryList.value = [];

  // 显示分类更改弹窗
  showCategoryChangeModal.value = true;
}

// 选择一级分类
function selectPrimaryCategory(item: any) {
  selectedPrimaryCategory.value = item;
  selectedSecondaryCategory.value = null; // 重置二级分类
  showPrimaryCategoryModal.value = false;

  // 获取二级分类数据
  getSecondaryCategoryData(item.id);
}

// 选择二级分类
function selectSecondaryCategory(item: any) {
  selectedSecondaryCategory.value = item;
  showSecondaryCategoryModal.value = false;
}

// 获取二级分类数据
async function getSecondaryCategoryData(categoryId: string | number) {
  try {
    const res = await getCategoryTwo({
      name: Number(categoryId), // 分类ID
      page: 1,
      limit: 10000,
    });

    if (res.code === 200 && res.data) {
      secondaryCategoryList.value = res.data.data || [];
    }
  }
  catch (error) {
    console.error('获取二级分类失败', error);
  }
}

// 确认分类更改
function confirmCategoryChange() {
  if (!selectedPrimaryCategory.value) {
    uni.showToast({
      title: '请选择一级分类',
      icon: 'none',
    });
    return;
  }

  uni.showModal({
    title: '确认更改',
    content: `确定要将选中的${selectedGoodsIds.value.length}个货品更改为"${selectedPrimaryCategory.value.name}${selectedSecondaryCategory.value ? ` - ${selectedSecondaryCategory.value.name}` : ''}"分类吗？`,
    success(res) {
      if (res.confirm) {
        // 调用批量更改分类接口
        const params = {
          goods_ids: selectedGoodsIds.value,
          cate_id: selectedPrimaryCategory.value.id,
          cate_id2: selectedSecondaryCategory.value?.id || 0,
        };

        console.log('批量更改分类参数:', params);

        edcategory(params)
          .then((res: any) => {
            if (res.code === 200) {
              uni.showToast({
                title: '更改成功',
                icon: 'success',
                duration: 2000,
              });

              // 关闭弹窗
              showCategoryChangeModal.value = false;
              // 清空选中状态
              selectedGoodsIds.value = [];
              // 重新加载数据
              loadData(true);
            }
            else {
              uni.showToast({
                title: res.msg || '更改失败',
                icon: 'none',
                duration: 2000,
              });
            }
          })
          .catch((err: any) => {
            console.error('批量更改分类失败:', err);
            uni.showToast({
              title: '更改失败',
              icon: 'none',
              duration: 2000,
            });
          });
      }
    },
  });
}

// 处理批量导入
function handleBatchImport() {
  if (selectedGoodsIds.value.length === 0) {
    uni.showToast({
      title: '请先选择要导入的货品',
      icon: 'none',
    });
    return;
  }

  uni.showModal({
    title: '确认导入',
    content: `确定要导入选中的${selectedGoodsIds.value.length}个货品吗？`,
    success(res) {
      if (res.confirm) {
        // 调用exportGoodsData接口
        let params = {};
        console.log(urlParams.value.catid);

        // 如果是从分类进入，添加catid参数
        if (urlParams.value.catid) {
          params = {
            goods_id: selectedGoodsIds.value,
            huozhu_id: '',
            huozhu_name: '',
            pici: '',
            pici_id: '',
            new_pici_status: false,
            license: '',
            new_pici: '',
            tab_index: 0,
            catid: urlParams.value.catid,
            catid_2: urlParams.value.catid_2 || '',
          };
        }
        else {
          params = {
            goods_id: selectedGoodsIds.value,
            huozhu_id: urlParams.value.huozhu_id || '',
            huozhu_name: urlParams.value.huozhu_name || '',
            pici: urlParams.value.pici ? Number(urlParams.value.pici) : 0,
            pici_id: urlParams.value.pici_id ? Number(urlParams.value.pici_id) : 0,
            new_pici_status: false,
            license: '',
            new_pici: '',
            tab_index: 1,
          };
        }

        console.log('批量导入参数:', params);

        exportGoodsData(params)
          .then((res: any) => {
            if (res.code === 200) {
              uni.showToast({
                title: '导入成功',
                icon: 'success',
                duration: 2000,
              });

              // 导入成功后，返回上一页
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
            else {
              uni.showToast({
                title: res.msg || '导入失败',
                icon: 'none',
                duration: 2000,
              });
            }
          })
          .catch((err: any) => {
            console.error('批量导入失败:', err);
            uni.showToast({
              title: '导入失败',
              icon: 'none',
              duration: 2000,
            });
          });
      }
    },
  });
}
</script>

<style scoped>
.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
}

.header-placeholder {
  height: 180rpx;
  /* 基础高度：头部 + 搜索框 */
}

.add-btn {
  background-color: #43cf7c;
  color: white;
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 10rpx;
  border: none;
}

.goods-card {
  display: flex;
  align-items: center;
  width: 92%;
  height: 64px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  margin: 6px auto 0 auto;
  padding: 0 12px;
}

.card-checkbox {
  margin-right: 8px;
}

.card-img {
  border-radius: 4px;
  margin-right: 12px;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card-title {
  font-size: 12px;
  font-weight: 600;
  color: #222;
  margin-bottom: 2px;
}

.card-unit {
  font-size: 8px;
  color: rgba(9, 214, 91, 1);
  border-radius: 2px;
  border: 1.5px solid #09d65b;
  padding: 1px 2px;
  background: #fff;
  display: inline-block;
  line-height: 1.2;
  font-weight: 600;
  margin-top: 4px;
  width: auto;
  min-width: 0;
  max-width: max-content;
  box-sizing: border-box;
}

.card-edit {
  margin-left: 10px;
  display: flex;
  align-items: center;
  height: 100%;
}

.edit-btn {
  width: 48px;
  height: 28px;
  background: #fff;
  color: #ff8d38;
  font-size: 12px;
  border-radius: 4px;
  border: 1px solid #ff8d38;
  display: flex;
  align-items: center;
  justify-content: center;
}

.goods-footer-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 200;

  height: 67px;
  background: #fff;
  border-radius: 4px;
  margin: 0 auto;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.06);
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.footer-checkbox {
  width: 22px;
  height: 22px;
  border-radius: 4px;
  border: 1.5px solid #eee;
  background: #fff;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.footer-checkbox.checked {
  background: #09d65b;
  border-color: #09d65b;
}

.footer-checkbox.checked::after {
  content: "";
  display: block;
  width: 12px;
  height: 12px;
  background: url('data:image/svg+xml;utf8,<svg fill="white" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M426.666667 725.333333a42.666667 42.666667 0 0 1-30.165334-12.501333l-170.666666-170.666667a42.666667 42.666667 0 1 1 60.330666-60.330666l140.501334 140.330666 311.168-311.168a42.666667 42.666667 0 1 1 60.330666 60.330667l-341.333334 341.333333a42.666667 42.666667 0 0 1-30.165333 12.501334z"></path></svg>') no-repeat center center;
  background-size: contain;
}

.footer-status {
  font-size: 13px;
  color: #222;
  margin-right: 16px;
  font-weight: 500;
  white-space: nowrap;
}

.footer-btn {
  min-width: 72px;
  height: 32px;
  border-radius: 5px;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
  padding: 0 10px;
  font-weight: 500;
  box-sizing: border-box;
  cursor: pointer;
  transition: all 0.2s;
}

.footer-btn-del {
  color: #ff4d4f;
  border: 1.2px solid #ff4d4f;
  background: #fff;
}

.footer-btn-type {
  color: #fff;
  background: #ff9800;
  border: 1.2px solid #ff9800;
}

/* 分类筛选样式 */
.category-filter-container {
  background: #fff;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-top: 124px;
}

.category-scroll-row {
  padding: 12rpx 16rpx;
  white-space: nowrap;
}

.subcategory-scroll-row {
  padding: 16rpx 20rpx 20rpx 20rpx;
  background: #f8f9fa;
  border-top: 1px solid #eee;
  white-space: nowrap;
}

.category-tag {
  display: inline-flex;
  align-items: center;
  padding: 12rpx 20rpx;
  background: #f5f5f5;
  border-radius: 20rpx;
  font-size: 26rpx;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
  border: 1px solid transparent;
  margin-right: 10rpx;
}

.category-tag:hover {
  background-color: #e8f4fd;
  transform: translateY(-1rpx);
}

.category-tag.active {
  background-color: #007aff;
  color: #fff;
  border-color: #007aff;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}

.category-tag.child-tag {
  background: #f0f0f0;
  font-size: 24rpx;
  padding: 10rpx 16rpx;
  color: #666;
  border-radius: 16rpx;
}

.category-tag.child-tag.active {
  background-color: #43cf7c;
  color: #fff;
  border-color: #43cf7c;
  box-shadow: 0 2px 8px rgba(67, 207, 124, 0.3);
}

.category-tag-text {
  font-weight: 500;
  white-space: nowrap;
  letter-spacing: 0.5rpx;
}

.expand-indicator {
  margin-left: 8rpx;
  font-size: 20rpx;
  font-weight: 600;
  width: 24rpx;
  height: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4rpx;
  transition: all 0.2s;
}

.category-tag.active .expand-indicator {
  background: rgba(255, 255, 255, 0.3);
  color: #fff;
}

/* 过渡动画 */
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.2s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

/* 空状态优化 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 30rpx;
  margin-bottom: 20rpx;
  color: #666;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  text-align: center;
  line-height: 1.5;
  margin-bottom: 40rpx;
}

/* 加载状态优化 */
.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 20rpx;
  color: #999;
}

.loading-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid #f3f3f3;
  border-top: 3rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 16rpx;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 表单行样式 */
.form-row {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  width: 120rpx;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #666;
  padding: 0 20rpx;
  min-height: 40rpx;
  display: flex;
  align-items: center;
}

/* 弹窗内容样式 */
.filter-content {
  background: #fff;
}
</style>
